import axios from 'axios';
import { setToken, getToken, removeToken } from './authToken';
import { ElMessage } from 'element-plus';
import { debounce } from 'lodash';

// 创建axios实例
const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, // api的base_url
  timeout: 5000, // 请求超时时间
});
 
// 请求拦截器
request.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = getToken();
    }
    return config;
  },
  error => {
    // 请求错误处理
    console.log(error); // for debug
    Promise.reject(error);
  }
);
 
// 响应拦截器
request.interceptors.response.use(
  response => {
    console.log(response.headers)
    if (response.headers.authorization) {
      // 登陆接口返回jwt
      setToken(response.headers.authorization)
    }
    // 对响应数据做处理，例如只返回data部分
    const res = response.data;
   
    return res;
  },
  error => {
    console.log('err' + error); // for debug
    if (error.response?.status === 401) {
      debounceMsg();
      removeToken();
      location.reload();
    }
    return Promise.reject(error);
  }
);
 

const debounceMsg = debounce((cb) => {
  ElMessage({
    type: 'error',
    message: '登录已失效！',
    plain: true,
  })
}, 100);

export default request;